<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-radio-group v-model="model" class="mb-[10px]" @change="handleQuery">
            <el-radio-button v-for="(item, index) in modelOptions" :key="'radio' + index" :label="item.label" :value="item.label" />
          </el-radio-group>
          <!-- <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="文件名" prop="roleName">
              <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="创建时间" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              ></el-date-picker>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form> -->
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button v-hasPermi="['origin:installation:upload']" type="primary" plain icon="Plus" @click="handleOriginUpload()"
              >上传原始装机清单</el-button
            >
          </el-col>
          <!-- <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar> -->
        </el-row>
      </template>

      <el-table ref="roleTableRef" v-loading="loading" :data="tableDatas">
        <el-table-column label="原始文件" prop="originalName" :show-overflow-tooltip="true" min-width="200" />
        <el-table-column label="转换文件" prop="track" :show-overflow-tooltip="true" min-width="200" />
        <el-table-column label="文件类型" prop="fileType" width="100" />
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button v-hasPermi="['system:menu:edit']" link type="primary" icon="Promotion" @click="handleDetail(scope)" />
            </el-tooltip>
            <el-tooltip content="下载" placement="top">
              <el-button v-hasPermi="['system:menu:edit']" link type="primary" icon="Download" @click="handleDownload(scope)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 上传原始装机清单 -->
    <el-dialog v-model="originDialog.visible" :title="originDialog.title" width="800px" append-to-body>
      <el-form ref="dialogFormRef" :model="dialogForm" label-width="80px" :rules="rules">
        <el-form-item label="机型" prop="aircraftModel">
          <el-radio-group v-model="dialogForm.aircraftModel">
            <el-radio v-for="(item, index) in modelOptions" :key="'model-item' + index" :value="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <el-upload
            style="width: 80%"
            :accept="fileType"
            action=""
            :auto-upload="false"
            :before-upload="handleBefore"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :on-change="handleChange"
          >
            <el-button type="primary">选择上传</el-button>
            <template v-if="fileType" #tip>
              <div class="el-upload__tip">只能上传{{ fileType }}文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="handleSure">确 定</el-button>
          <el-button :loading="buttonLoading" @click="handleCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OriginInstallationList" lang="ts">
import { uploadOriginListData, getOriginList } from '@/api/bomCompareTool/originInstallationList/index';
import { optionType, originInstallationVo, originInstallationQuery, originInstallationForm } from '@/api/bomCompareTool/originInstallationList/type';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const tableDatas = ref<originInstallationVo[]>();
const loading = ref(true);
const total = ref(0);
const showSearch = ref(true);
const buttonLoading = ref(false);
const model = ref('C919');
const queryFormRef = ref<ElFormInstance>();
const dialogFormRef = ref<ElFormInstance>();
const modelOptions = ref<Array<optionType>>([
  {
    label: 'C919',
    value: 'C919'
  },
  {
    label: 'C929',
    value: 'C929'
  }
]);
const data = reactive<PageData<originInstallationForm, originInstallationQuery>>({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  rules: {
    aircraftModel: [{ required: true, message: '机型不能为空', trigger: 'blur' }],
    file: [{ required: true, message: '原始清单文件不能为空', trigger: 'blur' }]
  }
});
const { queryParams, rules } = toRefs(data);
const fileType = ref('.xls,.xlsx');
const originDialog = ref<any>({
  title: '上传原始装机清单',
  visible: false
});
const dialogForm = ref<originInstallationForm>({
  aircraftModel: 'C919',
  file: null
});
/**
 * 查询角色列表
 */
const getList = () => {
  loading.value = true;
  getOriginList(model.value, queryParams.value).then((res) => {
    tableDatas.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
};

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置 */
const resetQuery = () => {
  // dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};
// 文件上传函数
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  dialogForm.value.file = null;
  dialogFormRef.value.validateField(['file']);
};
// 数据文件
const handleBefore: UploadProps['beforeUpload'] = (file) => {
  // let limit100M = file.size / 100 / 1024 / 1024 >= 1;
  // if (limit100M) {
  //     proxy?.$modal.msgError("单个文件大小应该小于100M！")
  //     return false
  // }
  const arr = file.name.split('.');
  const type = '.' + arr[arr.length - 1];
  const types = fileType.value.split(',');
  if (fileType.value && !types.includes(type)) {
    proxy?.$modal.msgError('请上传' + fileType.value + '文件！');
    return false;
  }
  return true;
};
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  proxy?.$modal.msgWarning(`当前限制选择1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + uploadFiles.length} 个文件！`);
};
const handleChange: UploadProps['onChange'] = (file: any, uploadFiles) => {
  const flag = handleBefore(file);
  if (!flag) {
    return false;
  }
  if (file.status === 'ready') {
    dialogForm.value.file = file.raw;
    dialogFormRef.value.validateField(['file']);
  }
};
const handleOriginUpload = () => {
  originDialog.value.visible = true;
};
// 上传文件创建标准装机清单
const handleSure = async () => {
  buttonLoading.value = true;
  let params = new FormData();
  params.set('file', dialogForm.value.file);
  let res = await uploadOriginListData(dialogForm.value.aircraftModel, params);
  buttonLoading.value = false;
  if (res.code === 200) {
    proxy?.$modal.msgSuccess('上传成功');
    handleQuery();
    originDialog.value.visible = false;
  }
};
const handleCancel = () => {
  originDialog.value.visible = false;
};
const handleDetail = (row: any) => {

};
const handleDownload = (row: any) => {

};

onMounted(() => {
  getList();
});
</script>
